//
//  TranscriptionView.swift
//  SpeechAnalyzerDemo
//
//  用于展示最终和临时转写文本的 UIKit 容器视图。
//  支持弹幕效果：TableView 显示完整句子，TextView 显示临时文本
//

import UIKit

final class TranscriptionView: UIView {

    private let textView = UITextView()
    private let placeholderLabel = UILabel()
    private let tableView = UITableView()
    private let tableViewTitleLabel = UILabel()

    // 弹幕消息数据源
    private var messages: [TranscriptionMessage] = []

    // 用于跟踪已处理的文本和已发送的句子
    private var previousFinalizedText: String = ""
    private var emittedSentences: Set<String> = []
    
    private var combinedAll:String = ""

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
        configureUI()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func update(finalized: String, volatile: String, confidence: Double?) {
        let combined = finalized + volatile

        // textView 直接显示原始文本，不做任何处理
        if combined.isEmpty {
            placeholderLabel.isHidden = false
            textView.isHidden = true
        } else {
            placeholderLabel.isHidden = true
            textView.isHidden = false
            textView.text = combined
            // 自动滚动到底部
            DispatchQueue.main.async { [weak self] in
                guard let self = self, !self.textView.text.isEmpty else { return }
                let bottom = NSRange(location: self.textView.text.count - 1, length: 1)
                self.textView.scrollRangeToVisible(bottom)
            }
        }

        // tableView 根据 finalized 文本进行断句处理
        processFinalizedText(finalized, confidence: confidence)
    }

    /// 处理 finalized 文本，提取新增的完整句子
    private func processFinalizedText(_ finalized: String, confidence: Double?) {
        // 如果文本没有变化，直接返回
        guard finalized != previousFinalizedText else { return }

        // 提取完整句子
        let sentences = extractSentences(from: finalized)

        // 添加新增的句子到 tableView
        for sentence in sentences {
            if !emittedSentences.contains(sentence) {
                emittedSentences.insert(sentence)
                addSentenceToTableView(sentence, confidence: confidence)
            }
        }

        // 更新已处理的文本
        previousFinalizedText = finalized
    }

    /// 从文本中提取完整句子
    private func extractSentences(from text: String) -> [String] {
        var sentences: [String] = []
        var currentSentence = ""

        // 句尾标点符号
        let endPunctuation: Set<Character> = ["。", "！", "？", ".", "!", "?"]

        // 使用占位符处理省略号，避免被误判
        let ellipsisPlaceholder = "\u{E000}"
        var processedText = text.replacingOccurrences(of: "…", with: ellipsisPlaceholder)
        processedText = processedText.replacingOccurrences(of: "...", with: ellipsisPlaceholder)

        for char in processedText {
            currentSentence.append(char)

            // 如果遇到句尾标点，结束当前句子
            if endPunctuation.contains(char) {
                // 还原省略号
                let restored = currentSentence.replacingOccurrences(of: ellipsisPlaceholder, with: "…")
                let trimmed = restored.trimmingCharacters(in: .whitespacesAndNewlines)

                if !trimmed.isEmpty {
                    sentences.append(trimmed)
                }
                currentSentence = ""
            }
        }

        return sentences
    }

    /// 添加句子到 tableView
    private func addSentenceToTableView(_ text: String, confidence: Double?) {
        let message = TranscriptionMessage(text: text, confidence: confidence)
        messages.append(message)

        tableView.reloadData()

        // 自动滚动到最后一行
        DispatchQueue.main.async { [weak self] in
            guard let self = self, !self.messages.isEmpty else { return }
            let lastIndexPath = IndexPath(row: self.messages.count - 1, section: 0)
            self.tableView.scrollToRow(at: lastIndexPath, at: .bottom, animated: true)
        }
    }

    /// 清空弹幕消息
    func clearMessages() {
        messages.removeAll()
        emittedSentences.removeAll()
        combinedAll = ""
        previousFinalizedText = ""
        tableView.reloadData()
    }
}

// MARK: - 布局与样式
private extension TranscriptionView {
    func setupLayout() {
        translatesAutoresizingMaskIntoConstraints = false
        layoutMargins = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)

        // TableView 容器
        let tableViewContainer = UIView()
        tableViewContainer.translatesAutoresizingMaskIntoConstraints = false
        tableViewContainer.addSubview(tableViewTitleLabel)
        tableViewContainer.addSubview(tableView)

        tableViewTitleLabel.translatesAutoresizingMaskIntoConstraints = false
        tableView.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            tableViewTitleLabel.topAnchor.constraint(equalTo: tableViewContainer.topAnchor),
            tableViewTitleLabel.leadingAnchor.constraint(equalTo: tableViewContainer.leadingAnchor),
            tableViewTitleLabel.trailingAnchor.constraint(equalTo: tableViewContainer.trailingAnchor),

            tableView.topAnchor.constraint(equalTo: tableViewTitleLabel.bottomAnchor, constant: 8),
            tableView.leadingAnchor.constraint(equalTo: tableViewContainer.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: tableViewContainer.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: tableViewContainer.bottomAnchor),
            tableView.heightAnchor.constraint(equalToConstant: 250)
        ])

        let containerStack = UIStackView(arrangedSubviews: [placeholderLabel, textView, tableViewContainer])
        containerStack.axis = .vertical
        containerStack.spacing = 16
        containerStack.translatesAutoresizingMaskIntoConstraints = false

        addSubview(containerStack)

        NSLayoutConstraint.activate([
            containerStack.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
            containerStack.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
            containerStack.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
            containerStack.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor)
        ])
    }

    func configureUI() {
        layer.borderColor = UIColor.separator.cgColor
        layer.borderWidth = 1 / UIScreen.main.scale
        layer.cornerRadius = 8

        textView.isEditable = false
        textView.isScrollEnabled = true
        textView.font = .preferredFont(forTextStyle: .body)
        textView.backgroundColor = .clear
        textView.textContainerInset = .zero
        textView.textContainer.lineFragmentPadding = 0
        textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true

        placeholderLabel.text = "No Transcripts Available."
        placeholderLabel.font = .preferredFont(forTextStyle: .subheadline)
        placeholderLabel.textColor = .secondaryLabel

        // TableView 标题
        tableViewTitleLabel.text = "转录历史 (弹幕)"
        tableViewTitleLabel.font = .preferredFont(forTextStyle: .subheadline)
        tableViewTitleLabel.textColor = .secondaryLabel

        // TableView 配置
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(TranscriptionMessageCell.self, forCellReuseIdentifier: "MessageCell")
        tableView.layer.borderColor = UIColor.separator.cgColor
        tableView.layer.borderWidth = 1 / UIScreen.main.scale
        tableView.layer.cornerRadius = 6
        tableView.separatorStyle = .singleLine
        tableView.backgroundColor = .systemBackground
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 44
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate
extension TranscriptionView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! TranscriptionMessageCell
        let message = messages[indexPath.row]
        cell.configure(with: message)
        return cell
    }
}

// MARK: - 自定义 Cell
private class TranscriptionMessageCell: UITableViewCell {
    private let messageLabel = UILabel()
    private let confidenceLabel = UILabel()
    private let timeLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        selectionStyle = .none

        messageLabel.numberOfLines = 0
        messageLabel.font = .preferredFont(forTextStyle: .body)
        messageLabel.textColor = .label

        confidenceLabel.font = .preferredFont(forTextStyle: .caption1)
        confidenceLabel.textColor = .secondaryLabel

        timeLabel.font = .preferredFont(forTextStyle: .caption2)
        timeLabel.textColor = .tertiaryLabel

        let infoStack = UIStackView(arrangedSubviews: [timeLabel, confidenceLabel])
        infoStack.axis = .horizontal
        infoStack.spacing = 8
        infoStack.distribution = .fillProportionally

        let mainStack = UIStackView(arrangedSubviews: [messageLabel, infoStack])
        mainStack.axis = .vertical
        mainStack.spacing = 4
        mainStack.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(mainStack)

        NSLayoutConstraint.activate([
            mainStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            mainStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 12),
            mainStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -12),
            mainStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8)
        ])
    }

    func configure(with message: TranscriptionMessage) {
        messageLabel.text = message.text

        if let confidence = message.confidence {
            confidenceLabel.text = String(format: "置信度: %.2f", confidence)
        } else {
            confidenceLabel.text = ""
        }

        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        timeLabel.text = formatter.string(from: message.timestamp)
    }
}
